package org.musicsweet.interceptor;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.musicsweet.anotation.AuthReq;
import org.musicsweet.entity.SysUser;
import org.musicsweet.exception.ServiceException;
import org.musicsweet.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @Aspect 面向切面编程  这是一个切面类
 * @Component java会自动扫描
 */
@Slf4j
@Component
@Aspect
public class AuthInterceptor {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 拦截 within（拦截的范围）
     * 带有@annotation ：requestMapping 和 authReq 这两个注解的
     *
     * @param joinPoint      拦截点
     * @param requestMapping 请求
     * @param authReq        需要鉴权的请求
     * @return 响应
     * @Around在我们写的代码前后加上一段代码逻辑
     */
    @Around("within(org.musicsweet..*) && @annotation(requestMapping) && @annotation(authReq)")
    public Object aroundController(ProceedingJoinPoint joinPoint, RequestMapping requestMapping, AuthReq authReq) throws Throwable {
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)) {
            throw new ServiceException("token不能为空");
        }
        SysUser sysUser = JSON.parseObject(redisUtil.get(token), SysUser.class);
        if (sysUser == null) {
            throw new ServiceException("token对象不存在");
        }
        //执行这个结果
        return joinPoint.proceed();
    }

}
